<script setup>
import Editor from '@tinymce/tinymce-vue'
import {ref} from 'vue';
const rawStr = ref('');
// 官网粘贴
// > https://www.tiny.cloud/docs/tinymce/6/file-image-upload/#images_upload_handler

const example_image_upload_handler = (blobInfo, progress) => new Promise((resolve, reject) => {
  const xhr = new XMLHttpRequest();
  xhr.withCredentials = false;
  xhr.open('POST', 'http://dida100.com:8889/api/upload');

  xhr.upload.onprogress = (e) => {
    progress(e.loaded / e.total * 100);
  };

  xhr.onload = () => {
    if (xhr.status === 403) {
      reject({ message: 'HTTP Error: ' + xhr.status, remove: true });
      return;
    }

    if (xhr.status < 200 || xhr.status >= 300) {
      reject('HTTP Error: ' + xhr.status);
      return;
    }

    const json = JSON.parse(xhr.responseText);

    // if (!json || typeof json.location != 'string') {
    //   reject('Invalid JSON: ' + xhr.responseText);
    //   return;
    // }

    resolve('http://dida100.com:8889'+json.file.path);
  };

  xhr.onerror = () => {
    reject('Image upload failed due to a XHR Transport error. Code: ' + xhr.status);
  };

  const formData = new FormData();
  formData.append('file', blobInfo.blob(), blobInfo.filename());

  xhr.send(formData);
});

// http://tinymce.ax-z.cn/demos/demo-classic.php
var init = {
        plugins: 'print preview searchreplace autolink directionality visualblocks visualchars fullscreen image link media template code codesample table charmap hr pagebreak nonbreaking anchor insertdatetime advlist lists wordcount imagetools textpattern help emoticons autosave bdmap indent2em autoresize formatpainter axupimgs',
    toolbar: 'image code undo redo restoredraft | cut copy paste pastetext | forecolor backcolor bold italic underline strikethrough link anchor | alignleft aligncenter alignright alignjustify outdent indent | \
    styleselect formatselect fontselect fontsizeselect | bullist numlist | blockquote subscript superscript removeformat | \
    table  media charmap emoticons hr pagebreak insertdatetime print preview | fullscreen | bdmap indent2em lineheight formatpainter axupimgs',
    height: 650, //编辑器高度
    min_height: 400,
    language:'zh_CN',
    
    images_upload_handler:example_image_upload_handler
    
}
</script>

<template>
  <main id="sample">
     <h1>富文本</h1>
     <p>{{ rawStr }}</p>
    <Editor
      v-model="rawStr"
      api-key="adolg3do84vg41ddoak4nwkas81yke42vopk0o9rsmfy9hyp"
      :init="init"
    />
  </main>
</template>

<style scoped>
.logo {
  display: block;
  margin: 0 auto 2rem;
}

@media (min-width: 1024px) {
  #sample {
    display: flex;
    flex-direction: column;
    place-items: center;
    width: 1000px;
  }
}
</style>